﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using GSQ.BusinessEntities;
using GSQ.BusinessLogic;
using UIapp.Interfaces;

namespace UIapp.Vistas
{
    public partial class frmProductos : Plantillas.frmViewPlantilla, IPantalla
    {
        public frmProductos(bool isView)
        {
            InitializeComponent();
            this.entityCollection = new List<PRODUCTOS>();
            this.lsbOriginales.DisplayMember = "NRO_ADICIONAL";
            this.lsbProductos.DisplayMember = "CODIGO";
            this._view = isView;
        }

        #region Variables
        List<PRODUCTOS> entityCollection;
        bool _hideCosto = false;
        bool _hidePrecio = false;
        bool _hideActivo = false;
        bool _view = true;
        #endregion

        #region Implementacion IPantalla
        public int ComandosSoportados
        {
            get
            {
                return (int)ComandosPantalla.Buscar |
                    (int)ComandosPantalla.Modificar |
                    (int)ComandosPantalla.Nuevo;
            }
        }

        public void Nuevo()
        {
            Dialogos.frmProductos frm = new Dialogos.frmProductos(null);
            frm.MdiParent = this.MdiParent;
            frm.Show();
        }

        public void Modificar()
        {
            if (this.bindingSource.Count > 0)
            {
                Dialogos.frmProductos frm = new Dialogos.frmProductos(new ProductosBL().GetById
                    (
                        ((PRODUCTOS)this.radGridView.CurrentRow.DataBoundItem).ID)
                    );
                frm.MdiParent = this.MdiParent;
                frm.Show();
            }
        }

        public void Eliminar()
        {
            throw new NotImplementedException();
        }

        public void Refrescar()
        {
            this.Buscar();
        }

        public void Buscar()
        {
            this.backgroundWorker.RunWorkerAsync();
            Comun.ShowLoadingFRM();
        }

        public void AgregarProducto(Controles.TransferEntity tranferEntity)
        {
            throw new NotImplementedException();
        }
        #endregion

        #region Tratamiento de eventos
        private void txtBuscar_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                this.timer1.Stop();
                this.Buscar();
                e.Handled = true;
            }
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            this.Listar();
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Comun.CloseLoadingFRM();
            this.pnlFastFind.Visible = false;
            if (e.Error != null)
                Comun.ShowMessage(e.Error);
            else
            {
                this.bindingSource.DataSource = this.entityCollection.ToList();
            }
        }

        private void frmProductos_Load(object sender, EventArgs e)
        {
            if (HideCosto)
                this.radGridView.Columns["ColumnCosto"].IsVisible = false;
            if (HidePrecio)
                this.radGridView.Columns["ColumnPrecio"].IsVisible = false;
            if (HidePrecio)
                this.radGridView.Columns["ColumnActivo"].IsVisible = false;
        }

        private void txtSearchValue_TextChanged(object sender, EventArgs e)
        {
            if (chkPorCodigo.IsChecked)
                if (this.txtSearchValue.Text.Trim().Length > 2 && this.txtSearchValue.Focused)
                {
                    this.timer1.Stop();
                    this.timer1.Start();
                }
                else
                {
                    this.timer1.Stop();
                    this.pnlFastFind.Visible = false;
                }
        }

        private void txtSearchValue_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Down)
            {
                e.Handled = true;
                if (this.lsbOriginales.Items.Count != 0 || this.lsbProductos.Items.Count != 0)
                {
                    if (this.pnlFastFind.Visible == true)
                    {
                        if (this.lsbOriginales.Items.Count > this.lsbProductos.Items.Count)
                        {
                            this.lsbOriginales.Focus();
                            this.lsbOriginales.Items[0].Selected = true;
                            // this.lsbOriginales.Items[0]. = true;
                        }
                        else
                        {
                            this.lsbProductos.Focus();
                            this.lsbProductos.Items[0].Selected = true;
                            //  this.lsbProductos.Items[0].foc = true;
                        }
                    }
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.BuscarFastFind();
            this.timer1.Stop();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.pnlFastFind.Visible = false;
            this.txtSearchValue.Focus();
        }

        private void lsbOriginales_DoubleClick(object sender, EventArgs e)
        {
            if (this.lsbOriginales.Items.Count > 0)
            {
                this.txtSearchValue.Text = this.lsbOriginales.SelectedItem.Text;
                this.Buscar();
                this.pnlFastFind.Visible = false;
            }
        }

        private void lsbProductos_DoubleClick(object sender, EventArgs e)
        {
            if (this.lsbProductos.Items.Count > 0)
            {
                this.txtSearchValue.Text = this.lsbProductos.SelectedItem.Text;
                this.Buscar();
                this.pnlFastFind.Visible = false;
            }
        }

        private void lsbOriginales_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Right)
            {
                e.Handled = true;
                this.lsbProductos.Focus();
            }
            else if (e.KeyData == Keys.Enter)
            {
                e.Handled = true;
                this.txtSearchValue.Text = this.lsbOriginales.SelectedItem.Text;
                this.Buscar();
                this.pnlFastFind.Visible = false;
            }
            else if (e.KeyData == Keys.Escape)
            {
                e.Handled = true;
                this.txtSearchValue.Focus();
                this.pnlFastFind.Visible = false;
            }
        }

        private void lsbProductos_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Left)
            {
                e.Handled = true;
                this.lsbOriginales.Focus();
            }
            else if (e.KeyData == Keys.Enter)
            {
                e.Handled = true;
                this.txtSearchValue.Text = this.lsbProductos.SelectedItem.Text;
                this.Buscar();
                this.pnlFastFind.Visible = false;
            }
            else if (e.KeyData == Keys.Escape)
            {
                e.Handled = true;
                this.txtSearchValue.Focus();
                this.pnlFastFind.Visible = false;
            }
        }

        private void radGridView_CellDoubleClick(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
        {
            if (!_view)
            {
                if (this.radGridView.RowCount > 0)
                {
                    if (((PRODUCTOS)this.radGridView.CurrentRow.DataBoundItem).ACTIVO)
                    {
                        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    }
                }
            }
        }
        #endregion

        #region Metodos auxiliares
        public void Listar()
        {
            this.entityCollection.Clear();
            this.pnlFastFind.Visible = false;
            decimal id = 0;
            if (this.txtSearchValue.Text.Trim() == string.Empty)
            {
                if (MessageBox.Show("¿Desea listar todos los registros? Esto puede tardar tiempo considerado.",

                    "Confirmación", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    this.entityCollection = new ProductosBL().GetAll();

                }
                else
                {
                    this.txtSearchValue.Focus();
                }
                return;
            }
            if (this.chkPorCodigo.IsChecked)
            {
                this.entityCollection = new ProductosBL().GetByCodigoTodos(this.txtSearchValue.Text.Trim());
            }
            else if (this.chkPorDescripcion.IsChecked)//Buscar por sting rnc
            {
                if (decimal.TryParse(this.txtSearchValue.Text.Trim(), out id))
                {
                    this.entityCollection = new ProductosBL().GetByDescripcion(id);
                }
                else
                {
                    this.entityCollection = new ProductosBL().GetByDescripcion(this.txtSearchValue.Text.Trim());
                }
            }
            else if (this.chkPorMarca.IsChecked)
            {
                if (decimal.TryParse(this.txtSearchValue.Text.Trim(), out id))
                {
                    this.entityCollection = new ProductosBL().GetByMarca(id);
                }
                else
                {
                    this.entityCollection = new ProductosBL().GetByMarca(this.txtSearchValue.Text.Trim());
                }
            }
            else if (this.chkPorCategoria.IsChecked)
            {
                if (decimal.TryParse(this.txtSearchValue.Text.Trim(), out id))
                {
                    this.entityCollection = new ProductosBL().GetByCategoria(id);
                }
                else
                {
                    this.entityCollection = new ProductosBL().GetByCategoria(this.txtSearchValue.Text.Trim());
                }
            }
            else if (this.chkPorDepartamento.IsChecked)
            {
                if (decimal.TryParse(this.txtSearchValue.Text.Trim(), out id))
                {
                    this.entityCollection = new ProductosBL().GetByDepartamento(id);
                }
                else
                {
                    this.entityCollection = new ProductosBL().GetByDepartamento(this.txtSearchValue.Text.Trim());
                }
            }
        }

        public bool HideCosto
        {
            get { return _hideCosto; }
            set { _hideCosto = value; }
        }

        public bool HidePrecio
        {
            get { return _hidePrecio; }
            set { _hidePrecio = value; }
        }

        public bool HideActivo
        {
            get { return _hideActivo; }
            set { _hideActivo = value; }
        }

        private void BuscarFastFind()
        {
            try
            {
                if (this.txtSearchValue.Focused  == true)
                {
                    Tuple<List<PRODUCTOS>, List<ORIGINALES_ADICIONALES>> fastFind = new ProductosBL().GetByStartWord(this.txtSearchValue.Text.Trim());

                    this.lsbOriginales.DataSource = fastFind.Item2;
                    this.lsbProductos.DataSource = fastFind.Item1;
                    if (this.lsbProductos.Items.Count > 0 || this.lsbOriginales.Items.Count > 0)
                    {
                        this.pnlFastFind.Location = new Point(this.txtSearchValue.Location.X + 160, this.txtSearchValue.Location.Y + 35);
                        this.pnlFastFind.Visible = true;
                    }
                    else
                        this.pnlFastFind.Visible = false;
                }
            }
            catch (Exception ex)
            {
                this.pnlFastFind.Visible = false;
                Comun.ShowMessage(ex.Message, MessageBoxIcon.Error);
            }
        }

        public PRODUCTOS SelectedProducto
        {
            get { return (PRODUCTOS)this.radGridView.CurrentRow.DataBoundItem; }
        }
        #endregion
    }
}
